<?php

namespace Luka\SecurityBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Luka\SecurityBundle\Form\LoginFormType;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Luka\SecurityBundle\Authentication\PartyUser;

class SecurityController extends Controller {
    public function loginAction() {
        $translator = $this->get('translator');
        $request = $this->get('request');
        $session = $this->get('session');

        $data = new LoginFormType($translator);
        $form = $this->get('form.factory')->create($data);

        $error = $this->FetchError($request, $session);

        if(empty($error)){
            if ('POST' == $request->getMethod()) {
                $form->bindRequest($request);
                if ($form->isValid()) {
                    $data->bindFormData($form->getData());
                    $em = $this->getDoctrine()->getEntityManager();

                    $party = $em->getRepository('LukaStoreBundle:Party')->findOneBy(array("username" => $data->getUsername()));

                    if ($party){
                        $partyUser = new PartyUser($party->getUsername(), $party->getPassword(), $party->getSalt(), array($party->getRole()->getName()));
                        $encoder = $this->container->get('security.encoder_factory')->getEncoder($partyUser);

                        /*
                        echo $encoder->encodePassword($data->getPassword(), $partyUser->getSalt());
                        exit;
                        */

                        if(!$encoder->isPasswordValid($partyUser->getPassword(), $data->getPassword(), $partyUser->getSalt())){
                            $session->setFlash('login-error', array($translator->trans('Vale parool!')));
                        }
                        else{
                            $token = new UsernamePasswordToken($party->getUsername(), null/*$party->getPassword()*/, 'main', array("ROLE_USER"));

                            //$session->setFlash('login-success', $translator->trans('Oled tuvastatud!'));

                            $this->container->get('security.context')->setToken($token);

                            return $this->redirect($this->generateUrl('_welcome'));
                        }
                    }
                    else{
                        $session->setFlash('login-error', $translator->trans('Kasutajat ei leitud!'));
                    }
                }
                else{
                    $session->setFlash('login-error', $form->getErrors());
                }
            }
        }
        else{
            $session->setFlash('login-error', array($error));
        }

        return $this->render('LukaSecurityBundle:Security:login.html.twig', array(
            'form' => $form->createView(),
        ));
    }

    private function FetchError($request, $session) {
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            return $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        }
        $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
        $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        return $error;
    }
}
